package com.jimmyhsu.nestedscrolldemo.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.view.NestedScrollingParent;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.OverScroller;

/**
 * Created by jimmyhsu on 2017/1/14.
 */

public class StickyNavLayout extends LinearLayout implements NestedScrollingParent {
    private float mTopViewHeight;
    private OverScroller mScroller;

    public StickyNavLayout(Context context) {
        this(context, null);
    }

    public StickyNavLayout(Context context, AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public StickyNavLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mScroller = new OverScroller(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        View pager = getChildAt(2);
        mTopViewHeight = getChildAt(0).getMeasuredHeight();
        ViewGroup.LayoutParams lp = pager.getLayoutParams();
        lp.height = getMeasuredHeight() - getChildAt(1).getMeasuredHeight();
    }

    @Override
    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
        return (nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0;
    }

    @Override
    public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
        boolean hideTop = dy > 0 && getScrollY() < mTopViewHeight;
        boolean showTop = dy < 0 && getScrollY() > 0 && !ViewCompat.canScrollVertically(target, -1);
        if (hideTop || showTop) {
            scrollBy(0, dy);
            consumed[1] = dy;
        }
    }

    @Override
    public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
        if (getScrollY() >= mTopViewHeight) {
            return false;
        }
        fling(velocityY);
        return true;
    }

    private void fling(float velY) {
        mScroller.fling(0, getScrollY(), 0, (int) velY, 0, 0, 0, (int) mTopViewHeight);
        invalidate();
    }

    @Override
    public void scrollTo(int x, int y) {
        if (y < 0) {
            y = 0;
        }
        if (y > mTopViewHeight) {
            y = (int) mTopViewHeight;
        }
        if (y != getScrollY()) {
            super.scrollTo(x, y);
        }
    }

//    public static float getActionBarSize(Context context) {
//
//        TypedArray actionbarSizeTypedArray = context.obtainStyledAttributes(new int[]{
//                android.R.attr.actionBarSize});
//        float height = actionbarSizeTypedArray.getDimension(0,0);
//        actionbarSizeTypedArray.recycle();
//        return height;
//
//    }
}
